package com.moxi.mogublog.sms.listener;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.HttpResponse;
import com.moxi.mogublog.sms.global.SysConf;
import com.moxi.mogublog.sms.util.SmsUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 短信监听器(用于更新Redis和索引)
 *
 * @author JackLi
 * @date 2020年05月28日
 */
@Component
public class SmsListener {

    private final static Logger log = LoggerFactory.getLogger(SmsUtil.class);

    @Autowired
    private SmsUtil smsUtil;

    /**
     * 发送短息
     * <p/>
     * RabbitListener —— 监听获取消息队列中的消息
     *
     * @param map
     */
    @RabbitListener(queues = "mogu.sms")
    public void sendSms(Map<String, String> map) {
        try {
            CommonResponse smsResponse = smsUtil.sendSms(
                    map.get("mobile"),
                    map.get("template_code"),
                    map.get("sign_name"),
                    " {\"code\":\"" + map.get("code") + "\"}");

            if (smsResponse != null) {
                // 200
                int httpStatus = smsResponse.getHttpStatus();
                // 对象
                HttpResponse httpResponse = smsResponse.getHttpResponse();

                // {"Message":"OK","RequestId":"5C22ED18-439B-4E7E-A1F7-5B4DACBFD7B7","BizId":"903716889257675441^0","Code":"OK"}
                String smsResponseData = smsResponse.getData();

                Map smsMap = JSON.parseObject(smsResponseData, Map.class);
                Object messageObj = smsMap.get(SysConf.MESSAGE);
                if (messageObj != null && StringUtils.isNotEmpty(messageObj.toString()) && StringUtils.equals(SysConf.OK, messageObj.toString())) {
                    // TODO 建议做一个数据库存储的行为，异步
                    log.info("短信发送成功");
                } else {
                    log.error("短信发送失败：" + smsResponseData);
                }
            }
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

}
